
const emit = (event, json) => {
    try {
        if (isIOS()) {
            window.webkit.messageHandlers[event].postMessage(json)
        } else {
            if (!json) {
                eval(`window.JSInterface.${event}()`)
            } else {
                let params = json
                if (typeof json !== 'string') {
                    params = JSON.stringify(json)
                }
                window.JSInterface[event](params)
            }
        }
    } catch (error) {
        console.log(error, '发送原生事件失败:' + event)
    }
}

const on = (event, callBack) => {
    window[event] = callBack;
};

const once = (event, callBack) => {
    window[event] = (res)=>{
		callBack && callBack(res);
		window[event] = undefined;
	};
};

const off = (event) => {
    window[event] = null;
}

const isIOS = () => {
    var userAgent = navigator.userAgent
    var isiOS = !!userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)

    return isiOS
}

const isAndroid = () => {
    var userAgent = navigator.userAgent
    var isAndroid = userAgent.indexOf('Android') > -1 || userAgent.indexOf('Adr') > -1

    return isAndroid
}

const invokeMethod = ({
	name,
	data,
	success,
	fail
})=>{
	try {
		emit(name,data);
		if (success) {
			on(name,(res)=>{
				success && success(res);
			});
		}
	} catch(e) {
		fail && fail(e);
	}

	return ()=>{
		off(name);
	};
}

const invokeMethodOnce = ({
	name,
	data,
	success,
	fail
})=>{
	try {
		emit(name,data);
		if (success) {
			on(name,(res)=>{
				success && success(res);
				off(name);
			});
		}
	} catch(e) {
		fail && fail(e);
		off(name);
	}
}


const MethodChannel = {
	invokeMethod,
	invokeMethodOnce,
	on,
	off,
	once,
	emit
}

export default MethodChannel;
